from crv.lib.base import BaseController
from tg import expose, flash, require, url, request, redirect
from pylons.i18n import ugettext as _, lazy_ugettext as l_
#from tg import redirect, validate
from crv.model import DBSession, metadata
from crv.model.crvmodel import *
from crv.controllers.error import ErrorController
from crv.controllers.crvcontroller import StatusController

from tw.mochikit import mochikit

from crv import model

from catwalk.tg2 import Catwalk
from repoze.what import predicates

__all__ = ['RootController']

class RootController(BaseController):
    admin = Catwalk(model, DBSession)

    status = StatusController()
    error = ErrorController()
   
    @expose('crv.templates.index')
    def index(self):
        return dict(page='index')

    @expose('crv.templates.about')
    def about(self):
        return dict(page='about')

    @expose('crv.templates.authentication')
    def auth(self):
        return dict()
    
    @expose('crv.templates.roles2')
    @require(predicates.not_anonymous("Only for logged in users"))
    def roles2(self):

        ###FOR TABLE###
        
        mochikit.inject()
        
        SC_table = ('SC_INITIALIZED', 'SC_STARTINGVM', 'SC_APPLYING', 'SC_RUNNING', 'SC_REMOVING', 'SC_STOPPINGVM', 'SC_FIXING', 'SC_EXCEPTION', 'SC_STOPPED', ' ', ' ', 'SC_STARTED') #this must match the list in crvmodel.py; STARTED = RUNNING, STOPPED = INITIALIZED so use mod len(SC_table)
        SC_colors = ('gray', 'cyan', 'yellow', 'green', 'orange', 'violet', 'saddlebrown', 'red') #these correspond to SC_table for color coding
        roles = DBSession.query(Role).all()

        ###FOR GRAPH###

        r = DBSession.query(Role).all()
        numRoles = len(r)
        maxDepOn = 0
        maxRow = 10 #maximum number of boxes in a row on graph
        temp = []
        rolelol = []#list of lists; each list has roles of certain number of dependOns
        notAuto = []#list of roles that are not autoroles
        #sort roles by number of dependOns
        for role in r:
            if role.getAttr("name").find("autorole") < 0:
                notAuto.append(role)
                if len(role.dependOn) > maxDepOn:
                    maxDepOn = len(role.dependOn)

        for i in range(0, maxDepOn+1):
            temp = []
            for role in r:
                if role.getAttr("name").find("autorole") < 0:
                    if len(role.dependOn) == i:
                        temp.append(role)
                        if len(temp) >= maxRow:
                            rolelol.append(temp[:])
                            temp = []
            if len(temp) > 0:
                rolelol.append(temp[:])

        #returns autorole if it finds auto; if not it returns str
        def find_auto(str):
            if str.find("autorole") < 0:
                return str
            else:
                return "autorole"
        
        return dict(roles = roles, SC_table = SC_table, SC_colors = SC_colors, mochikit = mochikit, rolelol = rolelol, numRoles = numRoles, notAuto = notAuto, find_auto = find_auto)        

    #some information is hidden until click on button to display
    #rolename is used to get the role from the list from the database, infotype is the type of information needed for display
    #text is sent in this form: [[section_title , [text, text, text,..]], [section_title, [text, text, text,...]], ...]
    @expose('crv.templates.disp')
    @require(predicates.not_anonymous("Only for logged in users"))
    def disprole(self, rolename, *infotype):
        roles = DBSession.query(Role).all()
        index = [role.getAttr("name") for role in roles].index(rolename);
        title = roles[index].getAttr("name") + ": " + " ".join(infotype);
        temp = []
        text = []
        for itype in infotype:
            temp = []
            if itype == 'attr':
                for att in roles[index].attr:
                    if len(att.value) <= 32:
                        temp.append(att.name+"="+att.value+" "+att.doc)
                    else:
                        temp.append(att.name+"="+att.value[0:20]+"..."+att.value[len(att.value)-12:len(att.value)]+" "+att.doc)
            elif itype == 'dependOn':
                temp = [obj.getAttr("name") for obj in roles[index].dependOn]
            elif itype == 'dependOnLocal':
                temp = [obj.getAttr("name") for obj in roles[index].dependOnLocal]      
            elif itype == 'dependBy':
                temp = [obj.getAttr("name") for obj in roles[index].dependBy]      
            elif itype == 'dependByLocal':
                temp = [obj.getAttr("name") for obj in roles[index].dependByLocal]
            text.append([roles[index].getAttr("name")+" "+itype, temp]);
            
        return dict(title = title, text = text)
                                

    @expose('crv.templates.vms2')
    @require(predicates.not_anonymous("Only for logged in users"))
    def vms2(self):
        mochikit.inject()

        SC_table = ('SC_INITIALIZED', 'SC_STARTING', 'SC_RUNNING', 'SC_STOPPING', 'SC_FIXING', 'SC_EXCEPTION', 'SC_STOPPED', ' ',  'SC_STARTED') #this must match the list in crvmodel.py; STARTED = RUNNING, STOPPED = INITIALIZED so use mod len(SC_table)
        SC_colors = ('gray', 'cyan', 'green', 'violet', 'saddlebrown', 'red') #these correspond to SC_table for color coding
        vms = DBSession.query(VM).all()

        return dict(vms = vms, SC_table = SC_table, SC_colors = SC_colors, mochikit = mochikit)

    #text is sent in this form: [[section_title , [text, text, text,..]], [section_title, [text, text, text,...]], ...]
    @expose('crv.templates.disp')
    @require(predicates.not_anonymous("Only for logged in users"))
    def dispvm(self, vmname, *infotype):
        vms = DBSession.query(VM).all()
        index = [vm.getAttr("name") for vm in vms].index(vmname);
        title = vms[index].getAttr("name") + ": " + " ".join(infotype)
        temp = []
        text = []
        for itype in infotype:
            temp = []
            if itype == 'attr':
                for att in vms[index].attr:
                    if len(att.value) <= 32:
                        temp.append(att.name+"="+att.value+" "+att.doc)
                    else:
                        temp.append(att.name+"="+att.value[0:20]+"..."+att.value[len(att.value)-12:len(att.value)]+" "+att.doc)
            elif itype == 'roles':
                temp = [obj.getAttr("name") for obj in vms[index].role]
            text.append([vms[index].getAttr("name") + " " + itype, temp]);

        return dict(title = title, text = text)

    @expose('crv.templates.clusters2')
    @require(predicates.not_anonymous("Only for logged in users"))
    def clusters2(self):
        mochikit.inject()

        SC_table = ('SC_INITIALIZED', 'SC_STARTING', 'SC_RUNNING', 'SC_STOPPING', 'SC_FIXING', 'SC_EXCEPTION', 'SC_STOPPED', ' ',  'SC_STARTED') #this must match the list in crvmodel.py; STARTED = RUNNING, STOPPED = INITIALIZED so use mod len(SC_table)
        SC_colors = ('gray', 'cyan', 'green', 'violet', 'saddlebrown', 'red') #these correspond to SC_table for color coding
        clusters = DBSession.query(Cluster).all()

        return dict(clusters = clusters, SC_table = SC_table, SC_colors = SC_colors, mochikit = mochikit)


    #text is sent in this form: [[section_title , [text, text, text,..]], [section_title, [text, text, text,...]], ...]
    @expose('crv.templates.disp')
    @require(predicates.not_anonymous("Only for logged in users"))
    def dispcl(self, clustername, *infotype):
        clusters = DBSession.query(Cluster).all()
        index = [cluster.getAttr("name") for cluster in clusters].index(clustername);
        title = clusters[index].getAttr("name") + ": " + " ".join(infotype)
        temp = []
        text = []
        for itype in infotype:
            temp = []
            if itype == 'attr':
                for att in clusters[index].attr:
                    if len(att.value) <= 32:
                        temp.append(att.name+"="+att.value+" "+att.doc)
                    else:
                        temp.append(att.name+"="+att.value[0:20]+"..."+att.value[len(att.value)-12:len(att.value)]+" "+att.doc)
            elif itype == 'roles':
                temp = [obj.getAttr("name") for obj in clusters[index].role]
            text.append([clusters[index].getAttr("name") + " " + itype, temp]);

        return dict(title = title, text = text)

    @expose('crv.templates.login')
    def login(self, came_from=url('/')):
        """Start the user login."""
        login_counter = request.environ['repoze.who.logins']
        if login_counter > 0:
            flash(_('Wrong credentials'), 'warning')
        return dict(page='login', login_counter=str(login_counter),
                    came_from=came_from)
    
    @expose()
    def post_login(self, came_from=url('/')):
        """
        Redirect the user to the initially requested page on successful
        authentication or redirect her back to the login page if login failed.
        
        """
        if not request.identity:
            login_counter = request.environ['repoze.who.logins'] + 1
            redirect(url('/login', came_from=came_from, __logins=login_counter))
        userid = request.identity['repoze.who.userid']
        flash(_('Welcome back, %s!') % userid)
        redirect(came_from)

    @expose()
    def post_logout(self, came_from=url('/')):
        """
        Redirect the user to the initially requested page on logout and say
        goodbye as well.
        
        """
        flash(_('We hope to see you soon!'))
        redirect(came_from)
    


    
